<template>
  <div id="reg">
    <div v-if="showReg">
      <p style="padding: 0.2rem 0.2rem 0rem 0.25rem;">为了您的账号更加安全，请绑定手机</p>
      <div class="reg">
        <group title="" class="weui-cells_form">
          <x-input v-model="formItem.phone" type="tel" title=" 手机号" class="weui-vcode" placeholder="请输入手机号" :max="11" :show-clear="false">
            <x-button :disabled="disabled" slot="right" type="primary" mini @click.native="sendCode">{{codebtn}}</x-button>
          </x-input>
          <x-input v-model="formItem.code" type="tel" title=" 验证码" class="weui-vcode" placeholder="请输入短信验证码" :max="4"></x-input>
          <x-input v-model="formItem.password" type="password" title="登录密码" class="weui-vcode" placeholder="请设置密码(6~16位),(选填)" :max="16" :min="6"></x-input>
        </group>
      </div>
      <div style="margin: 0.3rem 0.2rem 0.2rem 0.2rem">
        <x-button type="primary" :show-loading="loading" action-type="button" @click.native="handleReg">{{btn}}</x-button>
      </div>
    </div>
    <div id="container4" style="display: none;"></div>
  </div>
</template>
<script>
import PubHeader from '../components/PubHeader.vue'
import { checkTel } from '../libs/fn'
export default{
  components: {
    PubHeader
  },

  mounted() {

    var regmap, geolocation;
    //加载地图，调用浏览器定位服务
    regmap = new AMap.Map('container4', {
      resizeEnable: true
    });
    regmap.plugin('AMap.Geolocation', () => {
      geolocation = new AMap.Geolocation({
        enableHighAccuracy: true,//是否使用高精度定位，默认:true
        timeout: 60000,          //超过10秒后停止定位，默认：无穷大
        buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
        zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        buttonPosition:'RB'
      });
      regmap.addControl(geolocation);
      geolocation.getCurrentPosition();
      AMap.event.addListener(geolocation, 'complete', (data) => {
        this.showReg = true
        this.formItem.location = data.formattedAddress
        this.formItem.lat = data.position.lat
        this.formItem.lng = data.position.lng
        this.formItem.city_code = data.addressComponent.adcode
      });
      AMap.event.addListener(geolocation, 'error', (data) => {
        let errorMsg = data.info == 'FAILED'? '途鸟未获取到您的定位权限，不能完成绑定，请到设置中开启': '您的浏览器不支持定位，不能注册'
        this.$vux.confirm.show({
          title: '<i class="icon icon-gantanhao"></i>',
          content: errorMsg,
          confirmText: '刷新',
          cancelText: '返回',
          onCancel: () => {
            this.$router.go(-1)
          },
          onConfirm: () => {
            window.location.reload()
          }
        })
      });
    });
  },
  data() {
      return {
        showReg: false,
        loading: false,
        disabled: false,
        btn: '绑定',
        codebtn: '发送验证码',
        formItem: {
          phone: '',
          client: $config.client_type,
          device: $config.device_type,
          version: $config.version,
          password: '',
          code: '',
          os: 'wap',
          lat: '',
          lng:'',
          location: '',
          city_code: '',
          inviter_id: '',
          union_id: window.localStorage.unionid,
          device_code: 'wap',
          device_name: 'wap',
          face: window.localStorage.face,
          nick_name: window.localStorage.nickname
        }
      }
  },
  methods: {
    sendCode() {
      if(!checkTel(this.formItem.phone)) {
        this.$vux.toast.text('手机号码格式不正确', 'middle')
        return false
      }
      this.disabled = true
      this.codebtn = '正在发送...'
      this.$http.post($config.host + '/api/Userbase/getMessage', qs.stringify({
        phone: this.formItem.phone,
        type: 8
      })).then((res) => {
        const {code, msg} = res.data
        if(code == 1) {
          let i = $config.sendCodeTimer
          let timer = setInterval(() => {
            i--
            this.codebtn = i+'s发送成功'
            if(i <= 0) {
              clearInterval(timer)
              this.disabled = false
              this.codebtn = '重新发送'
            }
          }, 1000)
        } else {
          this.disabled = false
          this.codebtn = '获取验证码'
          this.$vux.toast.text(msg, 'middle')
        }
      }).catch((err) => {
        this.disabled = false
        this.codebtn = '获取验证码'
        this.$vux.toast.text($config.errMsg, 'middle')
      })


    },
    handleReg() {
      if(!checkTel(this.formItem.phone)) {
        this.$vux.toast.text('手机号码格式不正确', 'middle')
        return false
      }
      if(this.formItem.code.length < 4) {
        this.$vux.toast.text('请填写4位验证码', 'middle')
        return false
      }
      if((this.formItem.password.length < 6 || this.formItem.password.length > 16) && this.formItem.password) {
        this.$vux.toast.text('请填写6~16位密码', 'middle')
        return false
      }
      this.loading = true
      this.btn = '正在绑定中'
      this.$http.post($config.host + '/api/Thirdpartylogin/notThird', qs.stringify(this.formItem)).then((res) => {
        const {code, data, msg} = res.data
        if(code == 1){
          const isHttps = data.face.substring(0, 7)
          if(isHttps == 'http://'){
            data.face = data.face.replace(/http:\/\//, "https://")
          }
          let user = {
            uid: data.uid,
            phone: data.phone,
            status: data.status,
            token: data.token,
            verify_card: data.verify_card,
            verify_car: data.verify_car,
            verify_num: data.verify_num,
            level: data.level,
            service_id: data.service_id || '',
            nick_name: data.nick_name,
            fid: data.fid,
            city_code: this.formItem.city_code,
            order_pai: data.order_pai,
            lng: '',
            lat: '',
            face: data.face,
            location: ''
          }
          this.$store.commit('setUserInfo', user)
          //将登录数据保存在localStorage中
          window.localStorage.user = JSON.stringify(user)
          this.$router.push('bindSuccess')
        } else {
          this.loading = false
          this.btn = '重新绑定'
          this.$vux.toast.text(msg, 'middle')
        }
      }).catch((err) => {
        this.loading = false
        this.btn = '重新绑定'
        this.$vux.toast.text($config.errMsg, 'middle')
      })
    }
  }
}
</script>
<style scoped>
  .reg{
    margin: 0.2rem;
    background: #fff;
    height: auto;
    box-shadow: 0px 0px 0.15rem rgba(0, 0, 0, 0.07);
  }
</style>
